package com.Hsu.blog.controller;

import com.Hsu.blog.model.Result;
import com.Hsu.blog.model.UserInfo;
import com.Hsu.blog.service.UserService;
import com.Hsu.blog.utils.JwtUtils;
import com.Hsu.blog.utils.SecurityUtils;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Hsu琛君珩
 * @ClassName:UserController
 * @date 2024-01-24
 * @apiNote
 * @Version: v1.0
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName, String password){
        //1.参数校验
        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }
        //2.密码校验
        //获取数据库的密码
        UserInfo userInfo=userService.queryByName(userName);
        if(userInfo==null||userInfo.getId()<0){//非法
            return Result.fail("用户名或者密码错误");
        }
        //if(!password.equals(userInfo.getPassword())){
        //    return Result.fail("密码错误");
        //}
        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            return Result.fail("用户名或者密码错误");
        }
        //3.生成token，返回
        //密码已经正确
        Map<String,Object> claim=new HashMap<>();
        claim.put("id",userInfo.getId());
        claim.put("name",userInfo.getUserName());
        String token= JwtUtils.genToken(claim);
        return Result.success(token);
    }

    //获取登录用户的信息
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        //1.从token中获取用户Id
        String token=request.getHeader("user_token");
        //2.根据用户Id，获取用户信息
        Integer userId= JwtUtils.getUserIdFromToken(token);
        if(userId==null) {
            return null;
        }
        return userService.queryById(userId);
    }

    //获取当前作者的信息
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId==null||blogId<0){
            return null;
        }
        return userService.getAuthorInfo(blogId);
    }
}